<template>
  <view class="add-goods-container">
    <view class="form-container">
      <text class="page-title">添加商品</text>
      
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="label">商品名称</text>
          <u--input
            v-model="formData.name"
            placeholder="请输入商品名称"
            border="none"
            clearable
          ></u--input>
        </view>
        
        <view class="form-item">
          <text class="label">商品描述</text>
          <u--textarea
            v-model="formData.description"
            placeholder="请输入商品描述"
            border="none"
            maxlength="200"
            count
          ></u--textarea>
        </view>
        
        <view class="form-item">
          <text class="label">商品价格</text>
          <u--input
            v-model="formData.price"
            placeholder="请输入商品价格"
            border="none"
            type="digit"
            clearable
          ></u--input>
        </view>
        
        <view class="form-item">
          <text class="label">库存数量</text>
          <u--input
            v-model="formData.stock"
            placeholder="请输入库存数量"
            border="none"
            type="number"
            clearable
          ></u--input>
        </view>
      </view>
      
      <view class="form-section">
        <text class="section-title">商品图片</text>
        
        <view class="upload-section">
          <u-upload
            accept="image"
            :fileList="fileList"
            @afterRead="afterRead"
            @delete="deletePic"
            name="goods"
            :multiple="true"
            :maxCount="9"
            width="200"
            height="200"
            imageMode="aspectFit"
          >
            <view class="upload-item">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text class="upload-text">添加图片</text>
            </view>
          </u-upload>
        </view>
      </view>
    </view>
    
    <view class="bottom-action">
      <u-button
        :loading="loading"
        :disabled="loading"
        @click="submitForm"
        type="primary"
        size="large"
        customStyle="background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%); border: none; border-radius: 44rpx;"
      >
        {{ loading ? '提交中...' : '添加商品' }}
      </u-button>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import baseConfig from '@/config/baseUrl.js'

export default {
  name: 'AddGoods',
  
  data() {
    return {
      loading: false,
      fileList: [],
      formData: {
        name: '',
        description: '',
        price: '',
        stock: '',
        images: []
      }
    }
  },
  
  computed: {
    ...mapGetters(['openId'])
  },
  
  methods: {
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1)
    },
    
    // 新增图片
    async afterRead(event) {
      console.log('新增图片', event)
      let lists = [].concat(event.file)
      let fileListLen = this.fileList.length
      
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this.fileList[fileListLen]
        this.fileList.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: 'goods',
          url: result,
          fileName: `goods_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          filePath: result
        }))
        
        fileListLen++
      }
    },
    
    // 上传文件Promise
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
          filePath: url,
          name: 'file',
          success: (res) => {
            let data = JSON.parse(res.data)
            if (data.success) {
              resolve(data.message)
            } else {
              reject(new Error(data.message || '上传失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },
    
    // 提交表单
    async submitForm() {
      // 表单验证
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入商品名称',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.price) {
        uni.showToast({
          title: '请输入商品价格',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.stock) {
        uni.showToast({
          title: '请输入库存数量',
          icon: 'none'
        })
        return
      }
      
      if (this.fileList.length === 0) {
        uni.showToast({
          title: '请至少上传一张商品图片',
          icon: 'none'
        })
        return
      }
      
      this.loading = true
      
      try {
        // 收集图片URL
        const images = this.fileList.map(item => item.url).filter(url => url)
        
        const params = {
          openId: this.openId,
          name: this.formData.name,
          description: this.formData.description,
          price: parseFloat(this.formData.price),
          stock: parseInt(this.formData.stock),
          images: images,
          status: 1 // 默认上架
        }
        
        console.log('提交商品数据:', params)
        
        const res = await this.$api.addGoods(params)
        
        if (res.success) {
          uni.showToast({
            title: '商品添加成功',
            icon: 'success'
          })
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '添加失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('添加商品失败:', error)
        uni.showToast({
          title: '添加失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-goods-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.form-container {
  flex: 1;
  padding: 30rpx;
}

.page-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 40rpx;
  text-align: center;
}

.form-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30rpx;
  display: block;
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15rpx;
  display: block;
}

.upload-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.upload-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #c9cdd4;
  border-radius: 12rpx;
  background-color: #fafafa;
}

.upload-text {
  font-size: 24rpx;
  color: #c9cdd4;
  margin-top: 10rpx;
}

.bottom-action {
  padding: 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #ebeef5;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
}

// uView 组件样式调整
::v-deep .u-input {
  font-size: 28rpx;
  color: #303133;
}

::v-deep .u-textarea {
  .u-textarea__textarea {
    font-size: 28rpx;
    color: #303133;
  }
}

::v-deep .u-upload {
  .u-upload__button {
    margin-right: 0;
  }
}
</style>
